package com.wyb.util;


import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class JDBCUtils {
    //保证作用范围
    //只在本类中使用，应该是私有的
    private static DataSource dataSource = null;

    //使链接数据库的操作只在类加载中执行一次
    static {
        try (
                //1.读取配置文件
                //2.使配置文件路径的书写与物理路径解耦合
                //3.配置文件必须在src内部
                InputStream fis = JDBCUtils.class.getResourceAsStream("/JDBC.properties");
        ) {
            //创建properties集合
            Properties properties = new Properties();
            //将配置文件加载到集合中
            properties.load(fis);

            Class.forName(properties.getProperty("driverClassName"));
            //将内容从配置中取出
            dataSource = new DriverManagerDataSource(properties.getProperty("url"),
                    properties.getProperty("username"), properties.getProperty("password"));

        } catch (Exception e) {
            System.out.println("未知错误");
            e.printStackTrace();
        }
    }

    public static JdbcTemplate getTemplate() {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        return jdbcTemplate;
    }

    public static DataSource getDataSource() {
        return dataSource;
    }

    public static Connection startTransaction() {
        //1.开启线程绑定
        if (!TransactionSynchronizationManager.isSynchronizationActive()) {
            TransactionSynchronizationManager.initSynchronization();
        }
        //获取Connection连接
        Connection conn = DataSourceUtils.getConnection(dataSource);
        try {
            //开启事务
            conn.setAutoCommit(false);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return conn;
    }

    public static void commit(Connection conn) {
        try {
            //提交事务
            conn.commit();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            close(conn);
        }
    }

    public static void rollback(Connection conn) {
        try {
            conn.rollback();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            close(conn);
        }
    }

    public static void close(Connection conn) {
        //释放资源,关闭连接
        DataSourceUtils.releaseConnection(conn, getDataSource());
        //清空线程资源
        TransactionSynchronizationManager.clear();
        TransactionSynchronizationManager.unbindResourceIfPossible(getDataSource());
    }
}
